package org.lq.er.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.lq.er.dao.AnnouncementDao;
import org.lq.er.entity.Announcement;
import org.lq.er.util.Instantiation;
import org.lq.er.util.JDBCUtil;

//import com.sun.org.apache.xerces.internal.util.SynchronizedSymbolTable;

/**
 * 公告数据访问实现类
 * @author  张鹤山
 *
 */
public class AnnouncementDaoImpl implements AnnouncementDao, Instantiation<Announcement>{

	/**
	 * 添加公告
	 */
	@Override
	public int save(Announcement t) {
		String sql = "insert into announcement (information, release_time, alter_time) values(?,?,?)";
		int flag = 0;
		try {
			flag = JDBCUtil.executeUpdate(sql, t.getInformation(), t.getRelease_time(), t.getAlter_time());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 修改公告
	 */
	@Override
	public int update(Announcement t) {
		String sql = "update announcement set information=?, alter_time=? where id=?";
		int flag = 0;
		try {
			flag = JDBCUtil.executeUpdate(sql, t.getInformation(), t.getAlter_time(), t.getId());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 通过编号删除公告
	 */
	@Override
	public int delete(int id) {
		String sql = "delete from announcement where id=?";
		int flag = 0;
		try {
			flag = JDBCUtil.executeUpdate(sql, id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	/**
	 * 查询所有
	 */
	@Override
	public List<Announcement> findAll() {
		List<Announcement> list = new ArrayList<>();
		String sql = "select * from announcement order by alter_time desc";
		try {
			list = JDBCUtil.executeQuery(sql, this);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 根据编号查询公告
	 */
	@Override
	public Announcement getById(int id) {
		List<Announcement> list = new ArrayList<>();
		Announcement announcement = null;
		String sql = "select * from announcement where id=?";
		try {
			list = JDBCUtil.executeQuery(sql, this, id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if(list.size() == 0) {
			return null;
		}
		announcement = list.get(0);
		return announcement;
	}

	/**
	 * 实例化公告
	 */
	@Override
	public Announcement instance(ResultSet rs) {
		Announcement announcement = new Announcement();
		try {
			announcement.setId(rs.getInt("id"));
			announcement.setInformation(rs.getString("information"));
			announcement.setRelease_time(rs.getDate("release_time"));
			announcement.setAlter_time(rs.getDate("alter_time"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return announcement;
	}

}
